import React, { useEffect, useState, useRef } from 'react'
import { Card, Col, Row, List, Avatar, Drawer } from 'antd'
import { EditOutlined, EllipsisOutlined, SettingOutlined } from '@ant-design/icons'
import * as Echarts from 'echarts'
import _ from 'lodash'
import { getNews } from '@api'
import './index.scss'

export default function Home() {
  /*--------------------------------------state----------------------------------------------------------------------*/
  /*--------------------------------------state----------------------------------------------------------------------*/
  /*--------------------------------------state----------------------------------------------------------------------*/
  /*--------------------------------------state----------------------------------------------------------------------*/
  // 浏览新闻列表
  const [viewList, setviewList] = useState([])
  // 点赞新闻列表
  const [starList, setstarList] = useState([])
  // 所有新闻列表
  const [allList, setallList] = useState([])
  // 用户信息
  const { username, region, role: { roleName } } = JSON.parse(localStorage.getItem("token"))
  // 推出窗口
  const [visible, setvisible] = useState(false)
  // 柱状图
  const barRef = useRef()
  // 饼图
  const pieRef = useRef()
  /*--------------------------------------hooks调用方法----------------------------------------------------------------*/
  /*--------------------------------------hooks调用方法----------------------------------------------------------------*/
  /*--------------------------------------hooks调用方法----------------------------------------------------------------*/
  /*--------------------------------------hooks调用方法----------------------------------------------------------------*/
  useEffect(() => {
    get_view_news_list()
    get_star_news_list()
    get_all_news_list()
  }, [])
  /*--------------------------------------方法-------------------------------------------------------------------------*/
  /*--------------------------------------方法-------------------------------------------------------------------------*/
  /*--------------------------------------方法-------------------------------------------------------------------------*/
  /*--------------------------------------方法-------------------------------------------------------------------------*/
  // 获取浏览列表
  const get_view_news_list = () => {
    getNews({
      publishState: 2,
      _expand: 'category',
      _sort: 'view',
      _order: 'desc',
      _limit: 6
    }).then((res) => {
      setviewList(res.data)
    })
  }
  // 获取点赞列表
  const get_star_news_list = () => {
    getNews({
      publishState: 2,
      _expand: 'category',
      _sort: 'star',
      _order: 'desc',
      _limit: 6
    }).then((res) => {
      setstarList(res.data)
    })
  }
  // 获取所有新闻列表
  const get_all_news_list = () => {
    getNews({
      publishState: 2,
      _expand: 'category'
    }).then((res) => {
      setallList(res.data)
      newsBar(res.data)
    })
  }
  // 柱状图
  const newsBar = (obj) => {
    obj = _.groupBy(obj, item => item.category.title)
    let myNewsBar = Echarts.init(barRef.current);
    // 指定图表的配置项和数据
    let option = {
      title: {
        text: '新闻分类图示'
      },
      tooltip: {},
      legend: {
        data: ['数量']
      },
      xAxis: {
        data: Object.keys(obj),
        axisLabel: {
          rotate: "45",
          interval: 0
        }
      },
      yAxis: {
        // 最小间隔
        minInterval: 1
      },
      series: [{
        name: '数量',
        type: 'bar',
        data: Object.values(obj).map(item => item.length)
      }]
    }
    // 使用刚指定的配置项和数据显示图表。
    myNewsBar.setOption(option)
    // 屏幕改变大小时
    window.onresize = () => {
      myNewsBar.resize()
    }
  }
  // 新闻分布饼图
  const newsPie = async () => {
    await setvisible(true)
    // 先过滤出当前用户发布的新闻
    let currentList = allList.filter(item => item.author === username)
    // lodash转格式
    let groupObj = _.groupBy(currentList, item => item.category.title)
    var list = []
    for (var i in groupObj) {
      list.push({
        name: i,
        value: groupObj[i].length
      })
    }
    let myNewsPie = Echarts.init(pieRef.current)
    let option = {
      title: {
        text: '当前用户新闻分类图示',
        left: 'center'
      },
      toolbox: {
        show: true,
        feature: { }
      },
      series: [
        {
          name: '发布数量',
          type: 'pie',
          radius: [45, 100],
          center: ['50%', '50%'],
          roseType: 'area',
          data: list,
          itemStyle: {
            borderRadius: 8
          },
        }
      ]
    }
    myNewsPie.setOption(option)
  }
  /*--------------------------------------jsx--------------------------------------------------------------------------*/
  /*--------------------------------------jsx--------------------------------------------------------------------------*/
  /*--------------------------------------jsx--------------------------------------------------------------------------*/
  /*--------------------------------------jsx--------------------------------------------------------------------------*/
  return (
    <div>
      <Row gutter={16}>
        <Col span={9}>
          <Card title="用户最常浏览" bordered={true}>
            <List size="small" dataSource={viewList} renderItem={item => <List.Item><a href={`/news-manage/preview/${item.id}`}>{item.title}</a> </List.Item>} />
          </Card>
        </Col>
        <Col span={9}>
          <Card title="用户点赞最多" bordered={true}>
            <List size="small" dataSource={starList} renderItem={item => <List.Item><a href={`/news-manage/preview/${item.id}`}>{item.title}</a></List.Item>} />
          </Card>
        </Col>
        <Col span={6}>
          <Card
            cover={<img alt="example" src="https://gw.alipayobjects.com/zos/rmsportal/JiqGstEfoWAOHiTxclqi.png" />}
            actions={[<SettingOutlined key="setting" onClick={() => {newsPie()}} />, <EditOutlined key="edit" />, <EllipsisOutlined key="ellipsis" />,]} >
            <Card.Meta avatar={<Avatar src="https://joeschmoe.io/api/v1/random" />} title={username} description={<div> <b>{region ? region : "全球"}</b> <span style={{ paddingLeft: "30px" }}>{roleName}</span> </div>} />
          </Card>
        </Col>
      </Row>
      <Drawer width="500px" title="个人新闻分类" placement="right" closable={true} onClose={() => { setvisible(false) }} visible={visible} >
        <div ref={pieRef} style={{ width: '100%', height: "400px", marginTop: "30px" }}></div>
      </Drawer>
      <div ref={barRef} style={{ width: '100%', height: "400px", marginTop: "30px" }}></div>
    </div>
  )
}
